package com.invalid.android.BtInput;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Random;
import java.util.UUID;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

/**
 * This class does all the work for setting up and managing Bluetooth
 * connections with other devices. It has a thread that listens for
 * incoming connections, a thread for connecting with a device, and a
 * thread for performing data transmissions when connected.
 */
public class BluetoothChatService {
    // Debugging
    private static final String TAG = "BluetoothChatService";
    private static final boolean D = true;

    // Name for the SDP record when creating server socket
    private static final String NAME_SECURE = "BluetoothChatSecure";
    private static final String NAME_INSECURE = "BluetoothChatInsecure";

    // Unique UUID for this application
    private static final UUID MY_UUID_SECURE =
        UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private static final UUID MY_UUID_INSECURE =
        UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // Member fields
    private final BluetoothAdapter mAdapter;
    private final Handler mHandler;
    private AcceptThread mSecureAcceptThread;
    private AcceptThread mInsecureAcceptThread;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private int mState;
    
    private static final String BCAST_CONFIGCHANGED = "android.intent.action.CONFIGURATION_CHANGED";
    private static Context mContext;

    // Constants that indicate the current connection state
    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_LISTEN = 1;     // now listening for incoming connections
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 3;  // now connected to a remote device

    private int mScreenWidth;
    private int mScreenHeight;
  

  
    public BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent myIntent) {
            if (myIntent.getAction().equals( BCAST_CONFIGCHANGED ) ) {
                Log.d(TAG, "received->" + BCAST_CONFIGCHANGED);
                if(mContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
                    // it's Landscape
                    Log.d(TAG, "LANDSCAPE");
                }
                else {
                    Log.d(TAG, "PORTRAIT");
                }
            }
        }
    };
    
    /**
     * Constructor. Prepares a new BluetoothChat session.
     * @param context  The UI Activity Context
     * @param handler  A Handler to send messages back to the UI Activity
     */
    public BluetoothChatService(Context context, Handler handler) {
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mState = STATE_NONE;
        mHandler = handler;
    }

    /**
     * Set the current state of the chat connection
     * @param state  An integer defining the current connection state
     */
    private synchronized void setState(int state) {
        if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
        mState = state;

        // Give the new state to the Handler so the UI Activity can update
        mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
    }

    /**
     * Return the current connection state. */
    public synchronized int getState() {
        return mState;
    }
    
    public void updateSize()
    {
    	int v;
    	
    	v = mScreenHeight;
    	mScreenHeight = mScreenWidth;
    	mScreenWidth = v;
    	
		//mScreenHeight = getDisplayScreenHeight();// rawHeight;
		//mScreenWidth = getDisplayScreenWidth();// rawWidth;
    }

    /**
     * Start the chat service. Specifically start AcceptThread to begin a
     * session in listening (server) mode. Called by the Activity onResume() */
    public synchronized void start(Context cntx) {
        if (D) Log.d(TAG, "start");
        
        mContext = cntx;
        
      /*  Display display = ((Activity)cntx).getWindowManager().getDefaultDisplay();
        
		Method mGetRawH = null;
		try {
			mGetRawH = Display.class.getMethod("getRawHeight");
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Method mGetRawW = null;
		try {
			mGetRawW = Display.class.getMethod("getRawWidth");
		} catch (NoSuchMethodException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		int rawWidth = 0;
		try {
			rawWidth = (Integer) mGetRawW.invoke(display);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		int rawHeight = 0;
		try {
			rawHeight = (Integer) mGetRawH.invoke(display);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
        
      //  getDisplayScreenHeight();

		mScreenHeight = getDisplayScreenHeight();// rawHeight;
		mScreenWidth = getDisplayScreenWidth();// rawWidth;
		int o = mContext.getResources().getConfiguration().orientation;
    	if (o == Configuration.ORIENTATION_PORTRAIT) {
    		
    	}
    	else
    	{
    		int v;
    		v = mScreenHeight;
    		mScreenHeight = mScreenWidth;
    		mScreenWidth = v;
    	}

		Log.d(TAG, "screen width = " + mScreenWidth + " screen height = " + mScreenHeight);

        IntentFilter filter = new IntentFilter();
        filter.addAction(BCAST_CONFIGCHANGED);
        
     //   mContext.registerReceiver(mBroadcastReceiver, filter);

        // Cancel any thread attempting to make a connection
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        setState(STATE_LISTEN);

        // Start the thread to listen on a BluetoothServerSocket
        if (mSecureAcceptThread == null) {
            mSecureAcceptThread = new AcceptThread(true);
            mSecureAcceptThread.start();
        }
        if (mInsecureAcceptThread == null) {
            mInsecureAcceptThread = new AcceptThread(false);
            mInsecureAcceptThread.start();
        }
    }
    
    public int getDisplayScreenWidth()
    {
        int screenWidth = 0;
       
        DisplayMetrics metrics = new DisplayMetrics();
        Display display = ((Activity) mContext).getWindowManager().getDefaultDisplay();
        display.getMetrics(metrics);
       
        int ver = Build.VERSION.SDK_INT;
        if (ver < 13 || ver == 17)
        {
            screenWidth = metrics.widthPixels;
        }
        else if (ver == 13)
        {
            try {
                Method method = display.getClass().getMethod("getRealWidth");
                screenWidth = (Integer) method.invoke(display);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }    
        else if (ver > 13)
        {
            try {
                Method method = display.getClass().getMethod("getRawWidth");
                screenWidth = (Integer) method.invoke(display);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
       
        return screenWidth;
    }
    
    public int getDisplayScreenHeight()
    {
        int screenHeight = 0;
       
        DisplayMetrics metrics = new DisplayMetrics();
        Display display = ((Activity) mContext).getWindowManager().getDefaultDisplay();
        display.getMetrics(metrics);
       
        int ver = Build.VERSION.SDK_INT;
        if (ver < 13 || ver == 17)
        {
            screenHeight = metrics.heightPixels;
        }
        else if (ver == 13)
        {
            try {
                Method method = display.getClass().getMethod("getRealHeight");
                screenHeight = (Integer) method.invoke(display);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        else if (ver > 13)
        {
            try {
                Method method = display.getClass().getMethod("getRawHeight");
                screenHeight = (Integer) method.invoke(display);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
       
        return screenHeight;
    }

    /**
     * Start the ConnectThread to initiate a connection to a remote device.
     * @param device  The BluetoothDevice to connect
     * @param secure Socket Security type - Secure (true) , Insecure (false)
     */
    public synchronized void connect(BluetoothDevice device, boolean secure) {
        if (D) Log.d(TAG, "connect to: " + device);

        // Cancel any thread attempting to make a connection
        if (mState == STATE_CONNECTING) {
            if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        }

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        // Start the thread to connect with the given device
        mConnectThread = new ConnectThread(device, secure);
        mConnectThread.start();
        setState(STATE_CONNECTING);
    }

    /**
     * Start the ConnectedThread to begin managing a Bluetooth connection
     * @param socket  The BluetoothSocket on which the connection was made
     * @param device  The BluetoothDevice that has been connected
     */
    public synchronized void connected(BluetoothSocket socket, BluetoothDevice
            device, final String socketType) {
        if (D) Log.d(TAG, "connected, Socket Type:" + socketType);

        // Cancel the thread that completed the connection
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        // Cancel the accept thread because we only want to connect to one device
        if (mSecureAcceptThread != null) {
            mSecureAcceptThread.cancel();
            mSecureAcceptThread = null;
        }
        if (mInsecureAcceptThread != null) {
            mInsecureAcceptThread.cancel();
            mInsecureAcceptThread = null;
        }
        

        // Start the thread to manage the connection and perform transmissions
        mConnectedThread = new ConnectedThread(socket, socketType);
        mConnectedThread.start();

        // Send the name of the connected device back to the UI Activity
        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
        Bundle bundle = new Bundle();
        bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
        bundle.putString(BluetoothChat.DEVICE_ADDRESS, device.getAddress());
        msg.setData(bundle);
        mHandler.sendMessage(msg);

        setState(STATE_CONNECTED);
    }

    /**
     * Stop all threads
     */
    public synchronized void stop() {
        if (D) Log.d(TAG, "stop");

        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }

        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }

        if (mSecureAcceptThread != null) {
            mSecureAcceptThread.cancel();
            mSecureAcceptThread = null;
        }

        if (mInsecureAcceptThread != null) {
            mInsecureAcceptThread.cancel();
            mInsecureAcceptThread = null;
        }
        setState(STATE_NONE);
    }

    /**
     * Write to the ConnectedThread in an unsynchronized manner
     * @param out The bytes to write
     * @see ConnectedThread#write(byte[])
     */
    public void write(byte[] out) {
        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread
        synchronized (this) {
            if (mState != STATE_CONNECTED) return;
            r = mConnectedThread;
        }
        // Perform the write unsynchronized
        r.write(out);
    }

    /**
     * Indicate that the connection attempt failed and notify the UI Activity.
     */
    private void connectionFailed() {
        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(BluetoothChat.TOAST, mContext.getString(R.string.connect_error));
        msg.setData(bundle);
        mHandler.sendMessage(msg);

        mState = STATE_NONE; 
        // Start the service over to restart listening mode
        BluetoothChatService.this.start(mContext);
    }

    /**
     * Indicate that the connection was lost and notify the UI Activity.
     */
    private void connectionLost() {
        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(BluetoothChat.TOAST, mContext.getString(R.string.bt_disconnect));
        msg.setData(bundle);
        mHandler.sendMessage(msg);

        // Start the service over to restart listening mode
        BluetoothChatService.this.start(mContext);
    }

    /**
     * This thread runs while listening for incoming connections. It behaves
     * like a server-side client. It runs until a connection is accepted
     * (or until cancelled).
     */
    private class AcceptThread extends Thread {
        // The local server socket
        private final BluetoothServerSocket mmServerSocket;
        private String mSocketType;

        @TargetApi(10)
		public AcceptThread(boolean secure) {
            BluetoothServerSocket tmp = null;
            mSocketType = secure ? "Secure":"Insecure";

            // Create a new listening server socket
            try {
                if (secure) {
                    tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE,
                        MY_UUID_SECURE);
                } else {
                    tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(
                            NAME_INSECURE, MY_UUID_INSECURE);
                }
            } catch (IOException e) {
                Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e);
            }
            mmServerSocket = tmp;
        }

        @TargetApi(5)
		public void run() {
            if (D) Log.d(TAG, "Socket Type: " + mSocketType +
                    "BEGIN mAcceptThread" + this);
            setName("AcceptThread" + mSocketType);

            BluetoothSocket socket = null;

            // Listen to the server socket if we're not connected
            while (mState != STATE_CONNECTED) {
                try {
                    // This is a blocking call and will only return on a
                    // successful connection or an exception
                    socket = mmServerSocket.accept();
                } catch (IOException e) {
                    Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e);
                    break;
                }

                // If a connection was accepted
                if (socket != null) {
                    synchronized (BluetoothChatService.this) {
                        switch (mState) {
                        case STATE_LISTEN:
                        case STATE_CONNECTING:
                            // Situation normal. Start the connected thread.
                            connected(socket, socket.getRemoteDevice(),
                                    mSocketType);
                            break;
                        case STATE_NONE:
                        case STATE_CONNECTED:
                            // Either not ready or already connected. Terminate new socket.
                            try {
                                socket.close();
                            } catch (IOException e) {
                                Log.e(TAG, "Could not close unwanted socket", e);
                            }
                            break;
                        }
                    }
                }
            }
            if (D) Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType);

        }

        public void cancel() {
            if (D) Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this);
            try {
                mmServerSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e);
            }
        }
    }


    /**
     * This thread runs while attempting to make an outgoing connection
     * with a device. It runs straight through; the connection either
     * succeeds or fails.
     */
    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
        private String mSocketType;

        @TargetApi(10)
		public ConnectThread(BluetoothDevice device, boolean secure) {
            mmDevice = device;
            BluetoothSocket tmp = null;
            mSocketType = secure ? "Secure" : "Insecure";

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try {
                if (secure) {
                    tmp = device.createRfcommSocketToServiceRecord(
                            MY_UUID_SECURE);
                } else {
                    tmp = device.createInsecureRfcommSocketToServiceRecord(
                            MY_UUID_INSECURE);
                }
            } catch (IOException e) {
                Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
            }
            mmSocket = tmp;
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
            setName("ConnectThread" + mSocketType);

            // Always cancel discovery because it will slow down a connection
            mAdapter.cancelDiscovery();

            // Make a connection to the BluetoothSocket
            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception
                mmSocket.connect();
            } catch (IOException e) {
                // Close the socket
                try {
                    mmSocket.close();
                } catch (IOException e2) {
                    Log.e(TAG, "unable to close() " + mSocketType +
                            " socket during connection failure", e2);
                }
                connectionFailed();
                return;
            }

            // Reset the ConnectThread because we're done
            synchronized (BluetoothChatService.this) {
                mConnectThread = null;
            }

            // Start the connected thread
            connected(mmSocket, mmDevice, mSocketType);
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
            }
        }
    }

    /**
     * This thread runs during a connection with a remote device.
     * It handles all incoming and outgoing transmissions.
     */
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        
        private  Socket mEventSocket;
        private  BufferedReader mEventInStream;
        private  PrintWriter mEventOutStream;
               
    
        public ConnectedThread(BluetoothSocket socket, String socketType) {
            Log.d(TAG, "create ConnectedThread: " + socketType);
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "temp sockets not created", e);
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
            mEventSocket = null;
        }
        
        int[] convertCoord(String sx, String sy)
        {
        	int x;
        	int y;
        	int[] ret = new int[2];
        	
        	try 
        	{
	        	x = Integer.parseInt(sx);
	        	y = Integer.parseInt(sy);
	        	
	        	int w;
	        	int x0;
	        	int xmap;
	        	int ymap;
	        	
	        	//You should care about orientation here
	        	int o = mContext.getResources().getConfiguration().orientation;
	        	if (o == Configuration.ORIENTATION_PORTRAIT) {
	        		Log.d(TAG, "portrait");
	        		// vertical
		        	
		        	w = mScreenWidth * 480 / mScreenHeight;
		        	x0 = (800 - w) / 2;
		        	
		        	xmap = (x - x0) * mScreenWidth / w;
		        	ymap = y * mScreenHeight / 480;
		        	
		        	Log.d(TAG, "xmap = " + xmap + " ymap = " + ymap + "w = " + mScreenWidth + "h = " + mScreenHeight);
		        	x = xmap;
		        	y = ymap;
	        	} else if (o == Configuration.ORIENTATION_LANDSCAPE) {
	        		Log.d(TAG, "landscape");
	        		
	        	//	xmap = x; //(480 - y) *mScreenWidth / 480;
	        	//	ymap = y; //( x) * mScreenHeight / 800;
	        		
	        		xmap = (x) * mScreenHeight / 800;
	        		ymap = (y) * mScreenWidth / 480;
	        		
	        		x = xmap;
	        		y = ymap;
	        		
	        		Log.d(TAG, "xmap = " + xmap + " ymap = " + ymap + "w = " + mScreenWidth + "h = " + mScreenHeight);	        		
	        	}
        	
        	} catch (Exception e)
        	{
        		x = 0;
        		y = 0;
        		Log.i(TAG, "convert exception");
        		e.printStackTrace();
        	}
        	
        	ret[0] = x;
        	ret[1] = y;
        	
        	return ret;
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");
            byte[] buffer;
            int bytes;
            int old_x = 0;
            int old_y = 0;
            
            final int DOWN = 0;
            final int UP = 1;
            final int MOVE = 2;
            int state = UP;
            final String[] cmds = new String[1]; 
            int index = 0;
            
            int count = 1;
            
            
            if (mEventSocket == null)
            {
            	try {
					mEventSocket = new Socket("127.0.0.1", 8777);
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
            
        	BufferedReader bin = new BufferedReader(new InputStreamReader(
        			mmInStream));
            // Keep listening to the InputStream while connected
        	int value = 0;
        	boolean flag = false;
        	int errorcount = 0;
        	
        	outer:
            while (true) {
                try {
                    // Read from the InputStream 
                	String s1;
                	
                	while ((s1 = bin.readLine()) != null)
                	{
                		Log.i(TAG, "s =\"" + s1 + "\"");
                		count++;
                		if (count % 300 == 0)
                		{
                			if (errorcount >= 3)
                			{
                				// close connection
                				connectionLost();
                				break outer;
                			}
                			
                			Random r = new Random();
                			
                			byte[] b = new byte[10];
                			int v = r.nextInt() % 100;
                			value = v;
                			b[0] = (byte)v;
                			v = r.nextInt() % 100;
                			b[1] = (byte)v;
                			value += v;   // bluetooth should add the first two byte
                			
                			write(b);                
                			flag = true;
                		}
                		
                		if (s1.startsWith("res"))
                		{
                			String t = s1.substring(3);
                			int v1 = Integer.parseInt(t);
                			
                			if (v1 == value)
                			{
                				flag = false;
                				errorcount = 0;
                			}
                			else
                			{
                				flag = true;
                				errorcount++;
                			}
                			
                			continue;
                		}
                		
                		int  begin = s1.lastIndexOf('u');
                		if (begin == -1)
                		{
                			begin = s1.lastIndexOf('d');
                		}
                		
                		if (begin == -1)
                		{
                			continue;                 			
                		}

                		String s = s1.substring(begin);
                		
                		 String[] tokens = s.split(" ");                		 
                		 
                		 buffer = s.getBytes();
                		 bytes = s.length();
                         
                         int[] coord = convertCoord(tokens[1], tokens[2]);
                         StringBuffer sb = new StringBuffer();
                         if (tokens[0].equals("u"))
                         {
                         	sb.append("touch up ");
                         	state = UP;
                         	Log.w(TAG, "coord UP");
                         	old_x = 0;
                         	old_y = 0;
                         }
                         else if (tokens[0].equals("d"))
                         {
                        	if (state == UP)
                        	{
                        		sb.append("touch down ");
                        		state = DOWN;
                        		Log.w(TAG, "coord DOWN");
                        	}
                        	else if (state == DOWN)
                        	{
                        		if ((coord[0] - old_x) *(coord[0] - old_x) + (coord[1] - old_y) * (coord[1] - old_y) > 100)
                        		{
                        			sb.append("touch move ");
                            		state = MOVE;
                            		Log.w(TAG, "coord MOVE1");
                        		}
                        		else
                        		{
                        			Log.w(TAG, "coord MOVE1 remove");
                        			continue;
                        		}	
                        	}
                        	else if (state == MOVE)
                        	{
                        		sb.append("touch move ");
                        		Log.w(TAG, "coord MOVE2");
                        	}
                         	
                         }
                         else
                         {
                         	Log.w(TAG, "unsupport protocal");
                         	  mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                              .sendToTarget();
                         	continue;
                         }
                         
                         if (coord[0] < 0 || coord[1] < 0)
                         {
                        		Log.w(TAG, "coord error");
                        		mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                                .sendToTarget();
                           	  continue;
                         }
                         
                         old_x = coord[0];
                         old_y = coord[1];
                         
                         sb.append(coord[0]);
                         sb.append(" ");
                         sb.append(coord[1]);
                         sb.append("\n");
                         
                       //  if (index < 1024)
                        	 cmds[0] = new String(sb);                         
                         
                         writeEvent(cmds);
                         // Send the obtained bytes to the UI Activity
                         mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                         .sendToTarget();
                        
                	}
                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    
                   // connectionLost();
                    // Start the service over to restart listening mode
                   // BluetoothChatService.this.start(mContext);
                    break;
                }
            }
            
            try {
				bin.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
         
        void closeNetwork()
        {
        	if (mEventOutStream != null)
        	{
				mEventOutStream.close();
				mEventOutStream = null;
        	}
        	
    		try {
    			if (mEventInStream != null)
    				mEventInStream.close();
    			mEventInStream = null;
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		try {
    			if (mEventSocket != null)
    				mEventSocket.close();
    			mEventSocket = null;
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        }

        void writeEvent(String[] cmds) {
        	
        	if (mEventOutStream == null)
        	{
	        	try {
					mEventOutStream = new PrintWriter(mEventSocket.getOutputStream());
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
        	}
        	
        	if (mEventInStream == null)
        	{
	        	try {
					mEventInStream = new BufferedReader(new InputStreamReader(
											mEventSocket.getInputStream()));
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
        	}
    		String readline;
    			
			for (int i = 0; i < cmds.length; i++) {
				readline = cmds[i];
	
				if (!readline.equals("bye")) {
					mEventOutStream.println(readline);
					mEventOutStream.flush();
					
					Log.d(TAG, "Client:" + readline);
					try {
						String s = mEventInStream.readLine();
						Log.d(TAG, "Server:" + s);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
       	

        /**
         * Write to the connected OutStream.
         * @param buffer  The bytes to write
         */
        public void write(byte[] buffer) {
            try {
                mmOutStream.write(buffer);

                // Share the sent message back to the UI Activity
                mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "Exception during write", e);
            }
        }

        public void cancel() {
            try {
                mmSocket.close();
                closeNetwork();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        }
    }
    
}
